package com.example.voip;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.ocpsoft.prettytime.PrettyTime;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.adapter.CallRecordsAdapter;
import com.example.widget.CallDialog;

public class MainActivity extends Activity {

	private DisplayMetrics metrics;
	private LinearLayout bottom_ly;
	private String[] types = new String[]{"","ic_calllog_in","ic_calllog_out","ic_calllog_missed"};
	private ListView callrecords_lv;
	private TextView title_text;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		title_text = (TextView)findViewById(R.id.title_text);
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		bottom_ly = (LinearLayout)findViewById(R.id.bottom_ly);
		callrecords_lv = (ListView)findViewById(R.id.callrecords_lv);
		initCallRecords();
	}
	
	private void initCallRecords(){
		List<Map<String,String>> list = getCallRecords();
		callrecords_lv.setAdapter(new CallRecordsAdapter(this, list));
	}
	
	private List<Map<String,String>> getCallRecords(){
		ContentResolver cr = getContentResolver();
		PrettyTime pt = new PrettyTime(new Date());
		pt.setLocale(new Locale("ZH_CN"));
		final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, new String[] {CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,CallLog.Calls.TYPE, CallLog.Calls.DATE }, null, null,CallLog.Calls.DEFAULT_SORT_ORDER);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> map;
		while(cursor.moveToNext()){
			map = new HashMap<String,String>();
			int count = cursor.getColumnCount();
			map.put("num", cursor.getString(0));
			if(cursor.getString(1)!=null){
				map.put("name", cursor.getString(1));
			}else{
				map.put("name", cursor.getString(0));
			}
			map.put("type", types[Integer.parseInt(cursor.getString(2))]);
			map.put("time", pt.format(new Date(Long.parseLong(cursor.getString(3)))));
			list.add(map);
		}
		cursor.close();
		return list;
	} 
	
	public void callKeyBoard(View view){
		/*Intent i = new Intent(this,CallActivity.class);
		startActivity(i);*/
		bottom_ly.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
		new CallDialog(this,metrics,bottom_ly.getMeasuredHeight()).show();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		title_text.setText("首页");
	}
	
}
